package user

import (
	"api-go/model"
	"api-go/serializer"
	"fmt"
	"strconv"
	"time"
)

//获取前端传来的签到时间信息
type DakaTime struct {
	Data  string `form:"time"`
	Year  string `form:"year"`
	Month string `form:"month"`
	Type  string `form:"type"`
}

func (service *DakaTime) DakaToday(uid uint) *serializer.Response {

	//将用户Id转为string类型
	uidString := strconv.FormatUint(uint64(uid), 10)

	//根据Id判断当前日期是否已经打卡
	fmt.Println(service.Data)
	fmt.Printf("%T\n", service.Data)
	res := model.IsDakaByUserId(uidString, service.Data)

	if res {
		return serializer.ErrorResponse(serializer.CodeIsDaka)
	}

	dateToday := time.Now().Format("2006-01-02")

	//时间在今天之后无法签到
	t1, _ := time.Parse("2006-01-02", dateToday)
	t2, err := time.Parse("2006-01-02", service.Data)

	if err == nil && t1.Before(t2) {
		return serializer.ErrorResponse(serializer.CodeDakaError)
	}

	//打卡
	var code int = 1

	//如果签到日期为今天日期，则计算连续签到天数，否则不计算连续签到天数
	if t2 == t1 {
		//获取连续签到天数
		days := model.DakaRunningDays(uidString)

		num := days.Num

		//根据连续天数获取积分
		if 0 <= num && num < 7 {
			code = 1
		} else if 7 <= num && num < 30 {
			code = 3
		} else if 30 <= num && num < 365 {
			code = 5
		} else if num >= 365 {
			code = 10
		}
	}
	//使用积分签到的话就标记为1，否则为0
	var isUseCode int = 0

	if service.Type == "1" {
		isUseCode = 1
	}

	if isUseCode == 1 {
		//获取当前积分是否足够
		nowCode := model.DakaIntegral(uidString).Num
		if nowCode < 10 {
			return serializer.ErrorResponse(serializer.CodeIsNoAmple)
		}
	}

	ress := model.DakaByUserId(uidString, service.Data, code, isUseCode)
	if !ress {
		return serializer.ErrorResponse(serializer.CodeDakaError)
	}

	return serializer.OkResponse(nil)
}

//获取连续签到天数以及总积分
func (service *DakaTime) DakaInfo(uid uint) *serializer.Response {
	//将用户Id转为string类型
	uidString := strconv.FormatUint(uint64(uid), 10)

	//获取连续天数
	days := model.DakaRunningDays(uidString).Num

	//获取总积分
	code := model.DakaIntegral(uidString).Num

	result := map[string]interface{}{
		"days": days,
		"code": code,
	}
	return serializer.OkResponse(result)
}

//获取某年某月打卡数据
func (service *DakaTime) DakaInfoByMonth(uid uint) *serializer.Response {
	//将用户Id转为string类型
	uidString := strconv.FormatUint(uint64(uid), 10)

	//获取信息
	days := model.DakaDayByMonth(uidString, service.Year, service.Month)

	return serializer.OkResponse(days)
}

//判断今天是否已经签到
func (service *DakaTime) IsDakaToday(uid uint) *serializer.Response {
	//将用户Id转为string类型
	uidString := strconv.FormatUint(uint64(uid), 10)

	//根据Id判断当前日期是否已经打卡
	dateToday := time.Now().Format("2006-01-02")
	res := model.IsDakaByUserId(uidString, dateToday)

	if res {
		return serializer.OkResponse(true)
	}
	return serializer.OkResponse(false)
}
